import json
from datetime import datetime

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View
from lapi_app.models.user_model.user_info import Userinfo
from lapi_app.view.user_view.token_check import access_token


class User_info(View):

    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        if not access_token(data["user_id"]):
            return JsonResponse({
                "code": 1001,
                "message": "登录失效，请重新登录"
            })
        if data["account"] == "":
            users = Userinfo.objects.all().order_by("-id")
        else:
            users = Userinfo.objects.filter(account__contains=data["account"])
        size_page = data["size_page"]
        current_pages = data["current_page"]
        case_total = len(users)
        user_list = []
        for user in users:
            user_dict = {
                "user_id": user.id,
                "account": user.account,
                "username": user.username,
                "email": user.email,
                "email_password": user.email_password,
                "create_time": datetime.strftime(user.create_time, "%Y-%m-%d %H:%M:%S"),
                "update_time": datetime.strftime(user.update_time, "%Y-%m-%d %H:%M:%S")
            }
            user_list.append(user_dict)
        p = Paginator(user_list, size_page)
        page1 = p.page(current_pages)
        current_page = page1.object_list
        return JsonResponse({
            "code": 200,
            "message": "获取用户列表成功",
            "content": current_page,
            "case_total": case_total,
            "size_page": size_page,
            "current_page": current_pages
        })
